const multer = require('multer')
const moment = require('moment')
const path = require('path')
const fs = require('fs')
const mkdirsSync = require('../util/mkdirsSync')
const isFile = (_path) => fs.existsSync(_path)
const storage = multer.diskStorage({
  destination: async (req, file, cb) => {
    let date = moment(new Date()).format('YYYY-MM-DD')
    let directory = path.join(__dirname, `../uploads/${date}`)
    if (!isFile(directory)) {
      await mkdirsSync(directory)
      cb(null, directory)
    } else {
      cb(null, directory)
    }
  },
  filename (req, file, cb) {
    let fileArr = file.originalname.split('.')
    cb(null, `${fileArr[0]}-${Date.now()}.${fileArr[1]}`)
  }
})
const upload = multer({ storage }).single('file')
module.exports = [
  {
    url: '/api/upload',
    method: 'post',
    request: async (req, res) => {
      upload(req, res, function (err) {
        if (err) return res.status(400).json({msg: '上传失败'})
        res.json({msg: '上传成功'})
        // 一切都好
      })
    }
  }
]
